package com.quanquan.store.controller.marketActivity;

import DTO.PageDTO;
import com.alibaba.fastjson.JSON;
import com.quanquan.store.dto.CouponDTO;
import com.quanquan.store.dto.marketActivity.ScratchInfoDTO;
import com.quanquan.store.entity.marketActivity.GiftTypeEnum;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCard;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCardChance;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCardGift;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCardRecord;
import com.quanquan.store.request.CouponRequest;
import com.quanquan.store.request.marketActivity.ScratchCardRequest;
import com.quanquan.store.service.CouponService;
import com.quanquan.store.service.marketActivity.ScratchCardService;
import enums.ResCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import utils.DateUtils;
import utils.StringUtils;
import web.response.ResultBody;

import java.util.*;

@RestController
@RequestMapping("/marketActivity/scratchCard")
public class ScratchCardController {

    @Autowired
    private ScratchCardService scratchCardService;

    @Autowired
    private CouponService couponService;

    /**
     * 获取刮刮卡游戏信息
     * @param request
     * @return
     */
    @PostMapping("/getActivityInfo")
    public ResultBody getActivityInfo(@RequestBody ScratchCardRequest request) {

        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        ScratchCard scratchCard = scratchCardService.getById(request.getId());
        if (null == scratchCard || scratchCard.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        //进行中
        Integer goingStatus = 0;
        if(DateUtils.compare_date(scratchCard.getStartTime(),new Date()) > 0){
            goingStatus = -1;//未开始
        }
        if(DateUtils.compare_date(scratchCard.getEndTime(),new Date()) <= 0){
            goingStatus = 1;//已结束
        }

        Integer chance = 0;
        ScratchCardChance scratchCardChance = scratchCardService.getByIdAndUserId(scratchCard.getId(), request.getUserId());
        if(null != scratchCardChance){
            chance = scratchCardChance.getChance();
        }

        ScratchInfoDTO scratchInfoDTO = new ScratchInfoDTO();
        BeanUtils.copyProperties(scratchCard, scratchInfoDTO);
        scratchInfoDTO.setGoingStatus(goingStatus);
        scratchInfoDTO.setChance(chance);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", scratchInfoDTO);

    }

    /**
     * 添加刮刮卡游戏参与机会
     * @param request
     * @return
     */
    @PostMapping("/addChance")
    public ResultBody addChance(@RequestBody ScratchCardRequest request){
        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        ScratchCard scratchCard = scratchCardService.getById(request.getId());
        if (null == scratchCard || scratchCard.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        if(DateUtils.compare_date(scratchCard.getStartTime(),new Date()) > 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动未开始");
        }
        if(DateUtils.compare_date(scratchCard.getEndTime(),new Date()) <= 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动已结束");
        }

        ScratchCardChance scratchCardChance = scratchCardService.getByIdAndUserId(scratchCard.getId(), request.getUserId());
        if(null != scratchCardChance){
            scratchCardChance.setChance(scratchCardChance.getChance() + 1);
            scratchCardChance.setUpdateTime(new Date());
        }else{
            scratchCardChance = new ScratchCardChance();
            scratchCardChance.setUserId(request.getUserId());
            scratchCardChance.setScratchCardId(request.getId());
            scratchCardChance.setChance(1);
            scratchCardChance.setCreateTime(new Date());
            scratchCardChance.setUpdateTime(new Date());
        }

        scratchCardService.saveOrUpdate(scratchCardChance);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success");
    }


    /**
     * 刮刮卡抽奖
     * @param request
     * @return
     */
    @PostMapping("/getActivityGift")
    public ResultBody getActivityGift(@RequestBody ScratchCardRequest request){
        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        ScratchCard scratchCard = scratchCardService.getById(request.getId());
        if (null == scratchCard || scratchCard.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        if(DateUtils.compare_date(scratchCard.getStartTime(),new Date()) > 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动未开始");
        }
        if(DateUtils.compare_date(scratchCard.getEndTime(),new Date()) <= 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动已结束");
        }

        ScratchCardChance scratchCardChance = scratchCardService.getByIdAndUserId(scratchCard.getId(), request.getUserId());
        if(null == scratchCardChance || scratchCardChance.getChance() <= 0){
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "您的刮奖次数已用完，消费可获得刮奖机会哦");
        }

        scratchCardChance.setChance(scratchCardChance.getChance() -1);
        scratchCardChance = scratchCardService.saveOrUpdate(scratchCardChance);

//        Integer sumGiftOdds = scratchCardService.sumGiftOdds(request.getId());
//        if(null == sumGiftOdds){
//            sumGiftOdds = 0;
//        }
        int randOdds = (int)(Math.random()*100 + 1);

        ScratchCardGift gift = null;
        List<ScratchCardGift> list = scratchCardService.getGiftList(request.getId());
        int odds = 0;
        for (int i = 0; i < list.size(); i++) {
            odds += list.get(i).getOdds();
            if(odds >= randOdds){
                gift = list.get(i);
                break;
            }
        }

        System.out.println("随机奖品信息："+JSON.toJSONString(gift));
        String giftName = "您离中奖只差一步！";
        String giftImage = "";
        ScratchCardRecord record = new ScratchCardRecord();
        record.setUserId(request.getUserId());
        record.setScratchCardId(request.getId());
        record.setCreateTime(new Date());
        if(null == gift){
            record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
        }else{
            record.setGiftId(gift.getId());
            GiftTypeEnum giftType = GiftTypeEnum.getGiftType(gift.getGiftType());
            switch (giftType){
                case COUPON_GIFT:
                    CouponRequest couponRequest = new CouponRequest();
                    couponRequest.setUserId(request.getUserId());
                    couponRequest.setId(gift.getCouponId());
                    couponRequest.setCount(gift.getSendCount());
                    String sendResult = couponService.sendCoupon(couponRequest);
                    System.out.println("发券结果："+sendResult);
                    if("发券成功".equals(sendResult)){
                        //扣减库存
                        scratchCardService.substractGiftStock(gift.getId());

                        CouponDTO couponDTO = couponService.queryDetailsById(gift.getCouponId());
                        if(null != couponDTO){
//                            giftName = couponDTO.getName();
                            giftImage = couponDTO.getImage();
                        }
                        giftName = gift.getName();
                        record.setGiftType(GiftTypeEnum.COUPON_GIFT.getCode());
                        record.setCouponId(gift.getCouponId());
                    }else{
                        record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                    }
                    break;
                case POINT_GIFT:
                    break;
                default:
                    record.setGiftType(GiftTypeEnum.NO_GIF.getCode());
                    break;
            }
        }

        record = scratchCardService.saveOrUpdate(record);
        Map<String,Object> result = new HashMap<>();
        result.put("giftName",giftName);
        result.put("giftImage",giftImage);
        result.put("giftType",record.getGiftType());
        result.put("chance",scratchCardChance.getChance());

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success",result);

    }

    /**
     * 获取我的活动奖品
     * @param request
     * @return
     */
    @PostMapping("/getMyScratchCardGifts")
    public ResultBody getMyScratchCardGifts(@RequestBody ScratchCardRequest request){
        if (null == request.getId() || StringUtils.isEmpty(request.getUserId())) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        ScratchCard scratchCard = scratchCardService.getById(request.getId());
        if (null == scratchCard || scratchCard.getStatus() != 1) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        List<ScratchCardRecord> list = scratchCardService.getRecordList(request.getId(), request.getUserId());
        List<Object> result = new LinkedList<>();
        Map<String,Object> map = null;
        for (ScratchCardRecord record : list) {
            map = new HashMap<String,Object>();
            GiftTypeEnum giftType = GiftTypeEnum.getGiftType(record.getGiftType());
            switch (giftType){
                case COUPON_GIFT:
                    ScratchCardGift gift = scratchCardService.getGiftById(record.getGiftId());
                    map.put("giftName",gift.getName());
                    CouponDTO couponDTO = couponService.queryDetailsById(record.getCouponId());
                    map.put("giftImage",couponDTO.getImage());
                    map.put("createTime",DateUtils.dateToString(record.getCreateTime(),DateUtils.TIMESTAMP));
                    break;
                case POINT_GIFT:
                    break;
                default:
                    break;
            }

            result.add(map);
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success",result);
    }

    /**
     * 后台列表
     * @param request
     * @return
     */
    @PostMapping("/getAllScratchCardList")
    public ResultBody getAllScratchCardList(@RequestBody ScratchCardRequest request){
        PageDTO pageDTO = scratchCardService.findAllScratchCardByPage(request);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success",pageDTO);
    }

    /**
     * 添加或者修改活动信息
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public ResultBody edit(@RequestBody ScratchCardRequest request){

        System.out.println(JSON.toJSONString(request));
        ScratchCard scratchCard = null;
        if(null == request.getId()){
            scratchCard = new ScratchCard();
            scratchCard.setCreateTime(new Date());
        }else{
            scratchCard = scratchCardService.getById(request.getId());
            if(null == scratchCard){
                return new ResultBody(ResCodeEnum.CUSTOM.getCode(),"活动信息查询失败");
            }

            if(request.getStatus() == 2){
                scratchCard.setStatus(request.getStatus());
                scratchCardService.saveOrUpdate(scratchCard);
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
            }


        }
        scratchCard.setName(request.getName());
        scratchCard.setDescription(request.getDescription());
        scratchCard.setStatus(request.getStatus());
        scratchCard.setStartTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getStartTime()));
        scratchCard.setEndTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getEndTime()));

        scratchCardService.saveOrUpdate(scratchCard);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
    }

    /**
     * 后台获取信息
     * @param request
     * @return
     */
    @PostMapping("/getInfoById")
    public ResultBody getInfoById(@RequestBody ScratchCardRequest request) {

        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        ScratchCard scratchCard = scratchCardService.getById(request.getId());

        if (null == scratchCard) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "活动信息查询失败或已下架");
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", scratchCard);

    }

    /**
     * 后台获取活动奖项列表
     * @param request
     * @return
     */
    @PostMapping("/getScratchCardGifts")
    public ResultBody getScratchCardGifts(@RequestBody ScratchCardRequest request){
        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        PageDTO pageDTO = scratchCardService.getAllScratchGifts(request);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", pageDTO);
    }

    @PostMapping("/editGift")
    public ResultBody editGift(@RequestBody ScratchCardRequest request){
        System.out.println(JSON.toJSONString(request));
        ScratchCardGift scratchCardGift = null;
        if(null == request.getId()){
            scratchCardGift = new ScratchCardGift();
            scratchCardGift.setCreateTime(new Date());
            scratchCardGift.setRemainTotal(request.getSumTotal());
            scratchCardGift.setScratchCardId(request.getScratchCardId());
            scratchCardGift.setSendCount(request.getSendCount());
        }else{
            scratchCardGift = scratchCardService.getGiftById(request.getId());
            if(null == scratchCardGift){
                return new ResultBody(ResCodeEnum.CUSTOM.getCode(),"信息查询失败");
            }

            if(request.getStatus() == 2){
                scratchCardGift.setStatus(request.getStatus());
                scratchCardService.saveOrUpdate(scratchCardGift);
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
            }

        }
        scratchCardGift.setName(request.getName());
        scratchCardGift.setSumTotal(request.getSumTotal());
        scratchCardGift.setOdds(request.getOdds());
        scratchCardGift.setCouponId(request.getCouponId());
        scratchCardGift.setGiftType(request.getGiftType());
        scratchCardGift.setPoints(request.getPoints());
        scratchCardGift.setStatus(request.getStatus());
        scratchCardGift.setStartTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getStartTime()));
        scratchCardGift.setEndTime(DateUtils.parseStr2Date(DateUtils.DATE_SPACE_MINUTE,request.getEndTime()));
        scratchCardGift.setSendCount(request.getSendCount());
        scratchCardService.saveOrUpdate(scratchCardGift);

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),"success");
    }

    /**
     * 后台获取奖项详情
     * @param request
     * @return
     */
    @PostMapping("/getGiftInfoById")
    public ResultBody getGiftInfoById(@RequestBody ScratchCardRequest request) {

        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        ScratchCardGift scratchCardGift = scratchCardService.getGiftById(request.getId());

        if (null == scratchCardGift) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "信息查询失败");
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", scratchCardGift);

    }

    @PostMapping("/getScratchCardRecords")
    public ResultBody getScratchCardRecords(@RequestBody ScratchCardRequest request){
        if (null == request.getId()) {
            return new ResultBody(ResCodeEnum.CUSTOM.getCode(), "缺少必要参数");
        }

        PageDTO pageDTO = scratchCardService.getAllScratchRecords(request);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "success", pageDTO);
    }

}
